package kim.artemis.rpc.core.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import kim.artemis.rpc.core.protocol.serializer.ArtemisSerializer;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 解码
 * @author Wq.
 */
@Slf4j
public class ArtemisDecoder extends ByteToMessageDecoder {

    private Class<?> classz;
    private ArtemisSerializer serializer;


    public ArtemisDecoder(Class<?> classz, ArtemisSerializer serializer) {
        this.classz = classz;
        this.serializer = serializer;
    }


    @Override
    protected void decode(ChannelHandlerContext handlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        byteBuf.markReaderIndex();
        int dataLength = byteBuf.readInt();
        if (dataLength < 0) {
            handlerContext.close();
        }
        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        byteBuf.readBytes(data);

        Object object = serializer.deserialize(data, classz);
        list.add(object);
    }
}
